<template>
  <div v-if="refresh">
    <div class="container" v-if="getdata">
      <div class="index_dis">第{{index+1}}页</div>
      <div class="process">
        <div>
          <div v-for="item in translate" class="block" :style="status_block(item)"></div>
        </div>
        <div>
          <div v-for="item in proofread" class="block" :style="status_block(item)"></div>
        </div>
        <br>
        <span>翻译</span>
        &nbsp;
        <span>校对</span>
      </div>

      <transition-group name="fade">
        <div class="piccover" ref="piccover" v-for="(pic,i) in picsrclist" v-show="index===i" :key="i">
          <img :src="pic" class="pic" :ref="'pic'+i" alt="" @load="picload">
        </div>
      </transition-group>
      <transition name="fade">
        <div v-if="subtitledis" v-show="power!=='default'&&role!=='reader'">

          <div class="subleft">
            <div class="subtitles"
                 v-for="item in box_left"
                 :style="TextPosOp(subtitlelist[index].list[item.id])"
                 v-if="item"
            >
          <textarea class="subtitle" v-model="subtitlelist[index].list[item.id].data" :ref="'item-'+item.id" :disabled="power!=='root'"
                    :name="item.id"
                    @input="inputing"></textarea>
              <div class="del" :id="'del'+item.id" @click="del(item.id)">x</div>
              <div class="move" @mousedown="mousedown" :id="'move'+item.id"></div>
            </div>
          </div>
          <div class="subright">
            <div class="subtitles"
                 v-for="item in box_right"
                 v-if="item"
                 :style="TextPosOp(subtitlelist[index].list[item.id])">
          <textarea class="subtitle" v-model="subtitlelist[index].list[item.id].data" :ref="'item-'+item.id" :disabled="power!=='root'"
                    :name="item.id"
                    @input="inputing"></textarea>
              <div class="del" :id="'del'+item.id" @click="del(item.id)">x</div>
              <div class="move" @mousedown="mousedown" :id="'move'+item.id"></div>
            </div>
          </div>
          <div v-for="(temp,k) in loadedlist" v-if="showsvg&&temp">
            <div class="subtitlecover" v-for="(item,i) in subtitlelist[index].list" v-if="item" :key="i">
              <svg>
                <line
                  :x1="(item.left*rect.width+rect.left)"
                  :y1="(item.top*rect.height+rect.top)"
                  :x2="getboxX(item.id)"
                  :y2="getboxY(item.id)"
                  stroke="red"
                ></line>
                <circle
                  :cx="(item.left*rect.width+rect.left)"
                  :cy="(item.top*rect.height+rect.top)"
                  r="5"
                  stroke="red"
                  stroke-width="5"
                  fill="blue"
                  fill-opacity="0.0"
                >
                </circle>
              </svg>
            </div>
          </div>
        </div>
      </transition>
      <div class="arrow">
        <div @click="turn(-1)" v-show="index>0" :style="'left:'+(rect.left-350)+'px;'"></div>
        <div @click="turn(1)" v-show="index<piclist.length-1" :style="'left:'+(rect.right+305)+'px;'"></div>
      </div>
      <div class="status">
        <div class="translate" :style="status_style(translate[index])" @click="updatestatus('translator',translate[index])">翻译{{status_text(translate[index],'translator')}}</div>
        <div class="proofread" :style="status_style(proofread[index])" @click="updatestatus('proofreader',proofread[index])">校对{{status_text(proofread[index],'proofreader')}}</div>
      </div>
    </div>
  </div>
</template>

<script>
  import bus from '../assets/EventBus'
  export default {
    name: "Index",
    props:["login","power","role","username"],
    data() {
      return {
        refresh: true,
        selected: -1,
        getdata: false,
        coverrect: {},
        rect: {},
        zoom: 1,
        quality: 1,
        subtitledis: false,
        picsrclist: [""],

        translate:[{translators:'',translate_status:false}],
        proofread:[{proofreaders:'',proofread_status:false}],

        loadedlist: [],
        timer: null,

        box_left: [],
        box_right: [],

        showsvg: false,
        piclist: [],
        subtitlelist: [],
        index: -1,
        deltaX: 0,
        deltaY: 0,
        firstTimer:null
      }
    },
    methods: {
      mousedown(e) {
        if(this.power!=='default'&&this.power!=='guest'&&this.role!=='watcher') {
          this.selected = e.target.id.substr(4);
          const temprect = this.$refs['item-' + this.selected][0].getBoundingClientRect();
          this.subtitlelist[this.index].list[this.selected].text_moved = true;
          this.deltaX = e.clientX - temprect.left;
          this.deltaY = e.clientY - temprect.top + 30;
        }
      },
      inputing(e) {
        // console.log(e);
        const target = e.target.name;
        if (this.timer) {
          this.timer = window.clearTimeout(this.timer);
        }
        this.timer = window.setTimeout(() => {
          this.$http.post('/api/14ch/comic/changesubtitle', {
            id: target,
            text: this.subtitlelist[this.index].list[target].data,
            text_moved: this.subtitlelist[this.index].list[target].text_moved,
            text_x: this.subtitlelist[this.index].list[target].text_x,
            text_y: this.subtitlelist[this.index].list[target].text_y
          })
            .then(res => {
              // console.log('success');
            })
        }, 500)
      },
      TextPosOp(item) {
        let style;
        if (item.text_moved) {
          style = `position:fixed;left:${this.rect.width * item.text_x + this.rect.left}px;top:${this.rect.height * item.text_y + this.rect.top}px;width:200px;opacity: 0.8;`
        }
        return style;
      },
      findsubById(id) {
        for (let i = 0; i < this.subtitlelist[this.index].length; i++) {
          if (this.subtitlelist[this.index].list[i].id === id) {
            return i;
          }
        }
      },
      insertsubtitle(point_start_left, point_start_top, text_left, callback) {
        this.$http.post('/api/14ch/comic/addsubtitle', {
          workid: this.piclist[this.index].id,
          point_start_left: point_start_left,
          point_start_top: point_start_top,
          text_left: text_left
        }).then(res => {
          if (callback) callback();
        })
      },
      getpicurl(index) {
        return `/api/14ch/comic/pic/${this.piclist[index].url}?height=${document.documentElement.offsetHeight * this.zoom}&quality=${this.quality}`
      },
      changeindex(num = this.index) {
        if (!this.picsrclist[num]) {
          this.picsrclist[num] = this.getpicurl(num);
        }
        this.getdata = true;
        this.getsubtitlelist(num, () => {
          this.$nextTick(() => {
            this.showsvg = true;
          });

        });
      },
      getsubtitlelist(num = this.index, callback) {
        this.subtitledis = false;
        this.$http.post('/api/14ch/comic/getsubtitlelist', {workid: this.piclist[num].id})
          .then(res => {
            this.subtitlelist[num].list = [];
            for (const datum of res.data) {
              this.subtitlelist[num].list[parseInt(datum.id)] = {
                id: parseInt(datum.id),
                left: datum.point_start_left,
                top: datum.point_start_top,
                data: datum.text_data,
                isleft: datum.text_left,
                text_moved: datum.text_moved,
                text_x: datum.text_x,
                text_y: datum.text_y,
              };
              if (datum.text_left) {
                this.box_left.push({
                  id: parseInt(datum.id),
                });
              } else {
                this.box_right.push({
                  id: parseInt(datum.id),
                });
              }
            }
            this.box_left = [];
            this.box_right = [];
            this.subtitlelist[this.index].list.forEach(item => {
              if (item.isleft) {
                this.box_left.push({id: item.id})
              } else {
                this.box_right.push({id: item.id})
              }
            });
            this.subtitledis = true;
            if (callback) callback();
          });
      },
      getboxX(id) {
        let temp = this.$refs['item-' + id][0];
        if (temp) {
          temp = temp.getBoundingClientRect();
          if ((temp.top - 30 > this.subtitlelist[this.index].list[id].top * this.rect.height + this.rect.top) || (temp.bottom + 30< this.subtitlelist[this.index].list[id].top * this.rect.height + this.rect.top)) {
            return temp.left + temp.width / 2;
          } else if (temp.left + temp.width / 2 < this.subtitlelist[this.index].list[id].left * this.rect.width + this.rect.left) {
            return temp.right;
          } else {
            return temp.left;
          }
        }
      },
      getboxY(id) {
        let temp = this.$refs["item-" + id][0];
        if (temp) {
          temp = temp.getBoundingClientRect();
          if (temp.top - 30 > this.subtitlelist[this.index].list[id].top * this.rect.height + this.rect.top) {
            return temp.top;
          } else if (temp.bottom + 30 < this.subtitlelist[this.index].list[id].top * this.rect.height + this.rect.top) {
            return temp.bottom;
          } else {
            return temp.top + temp.height / 2;
          }
        }
        return 0;
      },
      del(id) {
        if(this.power==='root') {
          this.showsvg = false;
          this.$http.post('/api/14ch/comic/delsubtitle', {id: id}).then(res => {
            this.changeindex();
          })
        }
      },
      picload() {
        this.rect = {
          left: this.$refs["pic" + this.index][0].offsetParent.offsetLeft - this.$refs["pic" + this.index][0].offsetParent.clientWidth / 2 + this.$refs["pic" + this.index][0].offsetLeft - this.$refs["pic" + this.index][0].clientWidth / 2,
          right: this.$refs["pic" + this.index][0].offsetParent.offsetLeft - this.$refs["pic" + this.index][0].offsetParent.clientWidth / 2 + this.$refs["pic" + this.index][0].offsetLeft + this.$refs["pic" + this.index][0].clientWidth / 2,
          width: this.$refs["pic" + this.index][0].clientWidth,
          height: this.$refs["pic" + this.index][0].clientHeight,
          top: this.$refs["pic" + this.index][0].offsetParent.offsetTop + this.$refs["pic" + this.index][0].offsetTop,
          bottom: this.$refs["pic" + this.index][0].offsetParent.offsetTop + this.$refs["pic" + this.index][0].offsetTop + this.$refs["pic" + this.index][0].offsetHeight
        };
        this.loadedlist[this.index] = true;
        this.$refs["pic" + this.index][0].onmousedown = (e) => {
          e.preventDefault();
        };
        if (this.index<this.piclist.length-1&&!this.picsrclist[this.index+1]) {
          this.picsrclist[this.index+1] = this.getpicurl(this.index+1);
        }
        this.refresh = false;
        this.refresh = true;
      },
      updatestatus(mode,item){
        if((mode===this.role||this.role==='superuser')&&!item.status){
          this.$http.post('/api/14ch/comic/updatepiclist',{
            role:mode,
            username:this.username,
            status:true,
            id:this.piclist[this.index].id
          }).then(res=>{
            if(mode==='translator'){
              this.translate[this.index].user=this.username;
              this.translate[this.index].status=true;
            }else{
              this.proofread[this.index].user=this.username;
              this.proofread[this.index].status=true;
            }
            this.refresh=false;
            this.refresh=true;
          })
        }
      },
      turn(page){
        this.index+=page;
        if (this.index > this.piclist.length - 1) {
          this.index = this.piclist.length - 1;
        } else if (this.index < 0) {
          this.index = 0;
        } else {
          this.showsvg = false;
          this.changeindex(this.index);
        }
      },
      status_style(item){
        if(item.status){
          return 'color: #000000;' +
                 'text-shadow:0 0;' +
                 'font-weight:100;'+
                 'background:rgb(186, 255, 148);' +
                 'box-shadow:inset 0 -3px 3px white,0 0 2px #8d96a3;'
        }else{
          return '';
        }
      },
      status_block(item){
        if(item.status) {
          return 'height:' + 400 / this.piclist.length + 'px;' +
            ''
            ;
        }else{
          return 'height:' + 400 / this.piclist.length + 'px;' +
            'background:transparent'
            ;
        }
      },
      status_text(item,role){
        let str='';
        if(item.user){
          str+=':';
          str+=item.user;
        }else if(this.role===role||this.role==='superuser'){
          str+='打卡';
        }else{
          str+=':未完成';
        }
        return str;
      },
      init() {
        this.index = -1;
        this.getdata = false;
        this.showsvg = false;
        this.subtitlelist=[];
        this.loadedlist=[];
        this.translate=[];
        this.proofread=[];
        this.$http.post('/api/14ch/comic/getpiclist', {works: 'うどんの国の金色毛鞠 第07巻', episode: '第36话'}).then(res => {
          this.piclist = res.data;
          for (let i = 0; i < res.data.length; i++) {
            this.subtitlelist[i] = {id: res.data[i].id, list: []};
            this.picsrclist[i] = "";
            this.loadedlist[i] = false;
            this.translate[i] = {
              user:res.data[i].translator,
              status:!!(res.data[i].translator_status)
            };
            this.proofread[i] = {
              user:res.data[i].proofreader,
              status:!!(res.data[i].proofreader_status)
            }
          }
          this.index = 0;
          this.changeindex();

        });
      }
    }
    ,
    watch: {
      power(){
        this.$nextTick(()=>{
          this.refresh=false;
          this.showsvg=false;
          this.refresh=true;
          this.showsvg=true;
        })

      },
      role(){
        this.$nextTick(()=>{
          this.refresh=false;
          this.refresh=true;
        })
      }
    }
    ,
    computed: {}
    ,
    mounted() {
      this.init();
      window.addEventListener('mousedown', e => {
        if(this.power==='root') {
          if (!this.login && e.button === 0 && e.target.id.indexOf('move') < 0 && e.target.id.indexOf('del') < 0 && !e.target.name) {
            const cX = e.clientX, cY = e.clientY;
            if (cX < this.rect.left || cX > this.rect.right || cY < this.rect.top || cY > this.rect.bottom) {
              return true;
            }
            let flag = true;
            if (cX > this.rect.left + this.rect.width / 2) {
              flag = false;
            }
            this.showsvg = false;
            this.insertsubtitle(
              (cX - this.rect.left) / this.rect.width,
              (cY - this.rect.top) / this.rect.height,
              flag
              , () => {
                this.changeindex();
              });
          }
        }
      }, false);
      window.onmousewheel = e => {
        if(this.power==='default') return;
        if (e.deltaY > 0) {
          this.index++;
        } else {
          this.index--;
        }
        if (this.index > this.piclist.length - 1) {
          this.index = this.piclist.length - 1;
        } else if (this.index < 0) {
          this.index = 0;
        } else {
          this.showsvg = false;
          this.changeindex(this.index);
        }
      };
      document.onkeydown = e=>{
        if(this.power==='default') return;
        if(!e.target.name) {
          switch (e.key) {
            case 'ArrowUp':
            case 'ArrowLeft':
              this.index--;
              if (this.index > this.piclist.length - 1) {
                this.index = this.piclist.length - 1;
              } else if (this.index < 0) {
                this.index = 0;
              } else {
                this.showsvg = false;
                this.changeindex(this.index);
              }
              break;
            case 'ArrowDown':
            case 'ArrowRight':
              this.index++;
              if (this.index > this.piclist.length - 1) {
                this.index = this.piclist.length - 1;
              } else if (this.index < 0) {
                this.index = 0;
              } else {
                this.showsvg = false;
                this.changeindex(this.index);
              }
              break;
          }
        }
      }
      window.onresize = () => {
        this.init();
      };
      window.onreset = () => {
        this.init();
      };
      window.addEventListener('mouseup', () => {
        this.selected = -1;
      });
      window.addEventListener('mousemove', (e) => {
        if (this.selected > 0) {
          this.subtitlelist[this.index].list[this.selected].text_x = (e.x - this.deltaX - this.rect.left) / this.rect.width;
          this.subtitlelist[this.index].list[this.selected].text_y = (e.y - this.deltaY - this.rect.top) / this.rect.height;
          this.inputing({target: {name: this.selected}});
          this.refresh = false;
          this.refresh = true;
        }
      })
    }
  }
</script>

<style scoped>
  .container {
    height: 100%;
  }

  svg {
    z-index: -1;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
  }

  .index_dis {
    position: absolute;
    left: 50%;
    bottom: 20px;
    width: 100px;
    text-align: center;
    height: 26px;
    transform: translateX(-50%);
  }

  .piccover {
    background-color: #9c9c9c;
    position: absolute;
    min-width: 600px;
    height: 90%;

    top: 10px;
    left: 50%;
    transform: translateX(-50%);

  }

  .subtitlecover {
    position: fixed;
    z-index: 100;
    height: 100%;

  }
  .arrow>div{
    z-index:400;
    position:fixed;
    width: 40px;
    height: 40px;
    top: 50%;
    transform: translateY(-50%);
    background: #f2f2f2;
    border: 1px solid #c1c1c1;
    border-radius: 50%;
    cursor: pointer;
  }
  .arrow>div:hover{
    background: #fbfbfb;
    border-color: #a7f0ff;
  }
  .arrow>div:nth-child(1){
    left:20px;
  }
  .arrow>div:nth-child(1)::before{
    content: '';
    display: block;
    position:relative;
    left:-17px;
    top:10px;
    border: 10px solid transparent;
    border-right-color: rgba(156, 156, 156, 0.81);
  }
  .arrow>div:nth-child(2){
    right:20px;
  }
  .arrow>div:nth-child(2)::before{
    content: '';
    display: block;
    position: relative;
    top:10px;
    left:17px;
    border: 10px solid transparent;
    border-left-color: rgba(156, 156, 156, 0.81);
  }
  .subtitles {
    width: 100%;
    height: 80px;
    margin-top: 20px;
    margin-bottom: 20px;
  }

  .subtitles::before {
    content: '';
    display: block;
    position: relative;
    height: 10px;
    width: 35px;
    border: 1px solid transparent;
    border-bottom: 0;
    border-left: 20px solid red;
    border-right-width: 0;
    border-radius: 20px 20px 0 0;
    left: 5px;
    top: 1px;
    background: #ff8282;
  }

  .subtitle {
    z-index: 200;
    width: 100%;
    height: 100%;
    border: 1px solid red;
    font-size: 16px;
    resize: none;
    overflow: hidden;
    outline: none;
    border-radius: 3px;
  }
  .subtitle:disabled{
    background: rgb(255, 230, 173);
    color: #000000;
  }
  .subleft {
    position: absolute;
    right: calc(50% + 310px);
    width: 200px;
    height: 90%;
    top: 5%;
    z-index: 150;
  }

  .subright {
    position: absolute;
    left: calc(50% + 305px);
    width: 200px;
    height: 90%;
    top: 5%;
    z-index: 150;
  }

  .pic {
    height: calc(100% - 6px);
    position: absolute;
    left: 50%;
    top: 3px;
    transform: translate(-50%);
    user-select: none;
    user-focus: none;
    user-modify: none;
  }

  .del {
    position: relative;
    bottom: 101px;
    background: transparent;
    width: 20px;
    left: 6px;
    height: 10px;
    line-height: 10px;
    font-size: 8px;
    text-align: center;
    color: white;
    cursor: pointer;
    user-select: none;
  }

  .move {
    position: relative;
    width: 40px;
    height: 10px;
    background: transparent;
    bottom: 109px;
    left: 25px;
    cursor: pointer;
    user-select: none;
  }
  .status{
    z-index:500;
    position:fixed;
    left:20px;
    top:10px;
    /*width:150px;*/

    user-select: none;
  }
  .status>div{
    position:relative;
    margin:5px;
    margin-bottom:10px;
    min-width:150px;
    height:40px;
    color: #ffffff;
    font-weight: 800;
    text-shadow:0 0 4px #4b4b4b;
    border:2px solid transparent;
    text-align:center;
    line-height:40px;
    background: rgb(255, 173, 155);
    box-shadow: inset 0 -3px 3px #fbd1c4,0 0 2px #7c6176;
    border-radius: 3px;
    overflow: hidden;
    cursor: pointer;
    transition:all 1s ease;
  }
  .status>div:hover{
    border:2px solid #66cdff;
    transition:all 0.3s ease;
    transform: scale(1.2,1.2);
    transform-origin: center;
  }
  .translate{

  }
  .proofread{

  }
  .process{
    position:fixed;
    right:20px;
    top:10px;
    float:right;
  }
  .process>div{
    display:inline-block;
    margin:10px;
    background: #ff826f;
    width: 20px;
    height: 400px;
    border-radius: 10px;
    overflow: hidden;
  }
  .block{
    display:block;
    background: #a5ff5b;
    width:20px;
  }
  .fade-enter, .fade-leave-to {
    opacity: 0;
    /*transform: scale(0.5,0.5);*/
    /*transform-origin: left top;*/
  }

  .fade-enter-active, .fade-leave-active {
    transition: all 0.5s ease;

  }
</style>
